<?php

require_once( '../system/smarty.inc' );

require_once( '../system/tdao/Class_T_PATTERN.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );

require_once( '../system/Class_ERROR.php' );
require_once( '../system/login.inc.php' );
require_once( '../system/aoki_m.php' );
require_once( '../system/Class_PWD.php' );

Class_PWD::valid_auth(AOKI_AUTH_T_PATTERN,$login['staff_auth']);
/*
if   ($login['staff_auth'] == 'G-2' || $login['staff_auth'] == 'G-3')  {
	echo "権限はありません";
	exit;
}
*/
$dosearch = FALSE ;
$dao = new Class_T_PATTERN;
$matrix_cd = $_GET['matrix_cd'] ;
$dao->setTableNameWeek($matrix_cd);

/*
if ( isset( $_GET['csv'] ) &&  (  $_GET['csv'] == "download" ) ||
	 isset( $_GET['hist'] ) &&  (  $_GET['hist'] == "2" ) ) {
	$forms =  $_SESSION['MSEARCH']['INS_SHOP'];
}else {
	$forms = $_GET;
	$_SESSION['MSEARCH']['INS_SHOP'] = $forms;
}

$area_zone_flg  = 0;
if   ($login['staff_auth'] == 'G-2') {
	$area_zone_flg = 2;
}
if   ($login['staff_auth'] == 'G-3') {
	$area_zone_flg = 3;
}

$wherearr =  array();
if ( isset( $forms['block_cd'] ) &&  ( !empty( $forms['block_cd'] ) ) ){
	$wherearr[] = sprintf(" c.block_cd =  '%s' ",  $forms['block_cd'] );
}

if ( isset( $forms['shop_cd'] ) &&  ( !empty( $forms['shop_cd'] ) ) ){
	$wherearr[] = sprintf(" c.shop_cd =  '%s' ",  $forms['shop_cd'] );
}

if ( isset( $forms['upd_f'] ) &&  ( !empty( $forms['upd_f'] ) ) ){
	$wherearr[] = Class_PWD::get_u_time_where_sql($forms['upd_f'], 1, 'd' );
}

if ( isset( $forms['upd_t'] ) &&  ( !empty( $forms['upd_t'] ) ) ){
	$wherearr[] = Class_PWD::get_u_time_where_sql($forms['upd_t'],2, 'd' );
}
*/

//---CSVダウンロード　処理開始
if ( isset( $_GET['csv'] ) &&  (  $_GET['csv'] == "download" ) ){
	
	$_GET["csv"] = "";
	$tmpfilename = "pattern_delive".date("Ymd_His");
	header("Content-Type: application/octet-stream"); 
	header("Content-Disposition: attachment; filename=$tmpfilename.csv");
	
	$area_zone_flg  = 0;
	if   ($login['staff_auth'] == 'G-2') {
		$area_zone_flg = 2;
	}
	if   ($login['staff_auth'] == 'G-3') {
		$area_zone_flg = 3;
	}
	
	if   ($login['staff_auth'] == 'G-4') {
		$area_zone_flg = 4;
	}
	$patterns = $dao->getpatterns();
	$data = $dao->getDelives( $patterns, $area_zone_flg);
	
	
	 
	$colums = array();
	//列名
	
	/*
	$colums["name"]  = array('shop_cd','shop_name','media_name','delive_name');
	$colums["head"]  = array('店コード','店名','媒体','納品先' );

	$colums["pname"] = array();
	
	foreach ($patterns as $k => $v) {
		$colums["head"][] = $v["pattern_name"];
		$colums["pname"][] = $v["col"];
	}
	$colums["type"] = array();
	
	foreach ($colums as $k => $v) {
		$colums["type"][$v] = 1;
	}



	$colums["type"]["insert_conums"] = 2;
	*/
		$col_heads = array(
			'matrix_cd'        => array( 'マトリックスID',  1),
			'year4'            => array( '年度',            1),
			'week_cd'          => array( '週',              1),
			'flier_date'       => array( '折込日',          1),
			'shop_cd'          => array( '店舗コード',      1),
			'shop_name'        => array( '店名',            1),
			'media_name'       => array( '媒体',            1),
			'delive_cd'        => array( '納品先コード',    1),
			'delive_name'      => array( '納品先名',        1),
			'close_day'        => array( '締切日',          1),
			'close_time'       => array( '締切時間',        1)
		);
	//列名
	foreach ($col_heads as $k=>$v) {
		$colums["name"][]   = $k;
		$colums["head"][]   = $v[0];
		$colums["type"][$k] = $v[1];
	}
	foreach ($patterns as $k => $v) {
		$colums["head"][] = $v["pattern_name"];
		$colums["name"][] = $v["col"];
		$colums["type"][$v["col"]] = 1;
	}

	$col_heads_last = array(
		'u_time'        => array( '更新日時',       3),
		'c_time'        => array( '登録日時',       3)
	);
	foreach ($col_heads_last as $k=>$v) {
		$colums["name"][]   = $k;
		$colums["head"][]   = $v[0];
	}
		
	$week = Class_M_OTHER::get_by_matrix_cd( $matrix_cd );
	$week["flier_date"] =  Class_PWD::int8_to_dateD($week["flier_date"]);
	foreach ($data as $k=>$v){ 
		$data[$k]["matrix_cd"]   =  $matrix_cd;
		$data[$k]["year4"]       =  $week["year4"];
		$data[$k]["week_cd"]     =  $week["week_cd"];
		$data[$k]["flier_date"]  =  $week["flier_date"];
	}
	
	//$dao->output_csv($data, $colums);
	output_csv($data, $colums, $patterns);
	
	exit;
	
}

function  output_csv($data, $colums,$patterns )
{
	$old_shop_cd      = "";
	$old_delive_cd    = "";
	$old_media_name   = "";
	$sumlinearr       = false;
	
	if ( $colums["head"] ) {
		echo   mb_convert_encoding(implode(',',  $colums["head"]), "SJIS-win", "UTF-8")."\n";
	} else {
		echo  implode(',', $colums["name"])."\n";
	}
	
	$sumlinearr  = NULL;
	$shoparr = array();
	foreach ($data as $k => $v) {
		$shop_cd = $v["shop_cd"];
		if ( isset($shoparr[$shop_cd]) ) {
			$shoparr[$shop_cd] = $shoparr[$shop_cd] + 1;
		}else {
			$shoparr[$shop_cd] = 1;
		}
	}
	
	foreach ($data as $k => $v) {
		if ($shoparr[ $v["shop_cd"]] > 1) {
			if ( ($old_shop_cd  != $v["shop_cd"]) || ($old_media_name  != $v["media_name"])  ){
				if ($sumlinearr) {
					/*
					foreach ($sumlinearr as $kk=>$vv) {
						$sumlinearr[$kk] = empty($vv)?"":$vv;
					}
					*/
					echo  mb_convert_encoding(implode(',', $sumlinearr), "SJIS-win", "UTF-8")."\n";
				} 
				$old_shop_cd      = $v["shop_cd"] ;
				$old_media_name   = $v["media_name"] ;
				$old_delive_cd    = $v["delive_cd"] ;
				
				//$sumlinearr  = array("", "", "", "計");
				foreach ($colums["name"] as $kk => $vv) {
					$sumlinearr[$vv] = ""; 
				}
				$sumlinearr["shop_cd"]  = $old_shop_cd;
				$sumlinearr["shop_name"]  =  $v["shop_name"];
				$sumlinearr["media_name"]  =  $old_media_name;
			}
			
			foreach ($patterns as $kk => $vv) {
				 //$sumlinearr[$vv["col"]] = $v[$vv["col"]] ;
				 
				if ( !empty($v[$vv["col"]]) ){
					
					 $sumlinearr[$vv["col"]] = empty($sumlinearr[$vv["col"]]) ? $v[$vv["col"]] : $sumlinearr[$vv["col"]]  + $v[$vv["col"]];
				}
			}
			//print_r($v);  
			
			$linearr  = array();
			foreach ($colums["name"]  as $ck => $cv) {
				$linearr[]= $v[$cv];
			}
			
			/*
			foreach ($colums["pname"]  as $ck => $cv) {
				$linearr[]=  isset($v[$cv]) ?  $v[$cv] : "";
				$val    = isset($v[$cv]) ? nulltonum($v[$cv]) : 0;
				$valsum = isset($sumlinearr[$cv]) ? nulltonum($sumlinearr[$cv]) : 0;
				
				$sumlinearr[$cv] = $val + $valsum;
			}
			*/
			
			echo  mb_convert_encoding(implode(',', $linearr), "SJIS-win", "UTF-8")."\n";
		}
	}
	if ($sumlinearr){
		echo  mb_convert_encoding(implode(',', $sumlinearr), "SJIS-win", "UTF-8")."\n";
	}
	
	
}
function  nulltonum($value ){
	if (is_numeric($value)) {
		return (int)$value;
	}
	return 0;
}

//---CSVダウンロード　処理完了
$isG6_7 = FALSE;
if   ($login['staff_auth'] == 'G-2' || $login['staff_auth'] == 'G-3' || $login['staff_auth'] == 'G-4')  {
	$isG6_7 = TRUE;
}
//==================================周
if (empty($forms["year4"])) {
	$forms["year4"] = date('Y');
}
$smarty->assign('year4',  Class_PWD::get_years());

$week = Class_M_OTHER::get_week_array( $forms["year4"], PLEASE_SELECT_ARR, TRUE );

$smarty->assign('week', $week );
$smarty->assign('forms',  $forms);
//==================================周

$smarty->assign('isG6_7', $isG6_7 );

$smarty->assign('menu', $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );
//$smarty->assign('pageing', $smarty->fetch('page.html') );
$smarty->display('tpattern_delive.html');

?>